<?
$lUseAjax=1;
$pagename=LA_ADD_AD;

$lErrorPay=0;
$lPayCredits=0;
$lPayBold=0;
$lPayWYSIWYG=0;
$lPayPremium=0;
$lIsSpecial=0;
$lIsPremium=0;

if ($set_wysiwyg_editor)
$html_editor=1;

if (!$admin_area)
include_once("header_inc.php");

$tplItem=new TplLoad;

if (!$admin_area)
{
	check_valid_user("");
	include_once("member_header.php");
}
$ad_id=getParamInt("ad_id","");
$catid=getParamInt("ad_cat_id","");

$tplItem->assign("set_region","$set_region");
$tplItem->assign("phpself",$_SERVER['PHP_SELF']);
$tplItem->assign("set_expire_days_option",$set_expire_days_option);
$tplItem->assign("url", "http://$set_url");
$tplItem->assign("html_editor", "$html_editor");
$tplItem->assign("set_video_upload", "$set_video_upload");
$tplItem->assign("set_doc_upload", "$set_doc_upload");
$tplItem->assign("set_currency_text","$set_currency_text");

if ($admin_area)
$tplItem->assign("url_to_upload", "http://$set_url/admin/item_upload.php");
else
$tplItem->assign("url_to_upload", "http://$set_url/upload_file.php");

if ($admin_area)
$tplItem->assign("url_to_upload_video", "http://$set_url/admin/item_upload_video.php");
else
$tplItem->assign("url_to_upload_video", "http://$set_url/upload_video.php");

if ($admin_area)
$tplItem->assign("url_to_upload_doc", "http://$set_url/admin/item_upload_other.php");
else
$tplItem->assign("url_to_upload_doc", "http://$set_url/upload_other.php");
if (!$admin_area){
	$tplItem->assign("url_to_bold", "http://$set_url/member_extra.php");
}

$lCatCost="";

if ($ad_id)
{
	$result = q ("select a.*,c.* from $ads_tbl a left join $AdExtraOptions c ON a.ad_id=c.mv_ad_id  where a.ad_id = $ad_id");
	//logMsg("JMR -- Query item.php","select a.*,c.* from $ads_tbl a left join $AdExtraOptions c ON a.ad_id=c.mv_ad_id  where a.ad_id = $ad_id");	
	$row = mysql_fetch_array($result);
	$ad_owner = $row["ad_owner"];
	$lCatId = $row["ad_cat_id"];
	$lAdRegion=$row["ad_region"];
	$lAdProvincia=$row["ad_provincia"];
	//$lAdLocalidad=$row["ad_localidad_id"];
	$lAdLocalidadStr=$row["mv_localidad_name"];
	$lAdPrecio=$row["ad_precio"];
	$lAdMoneda=$row["ad_moneda"];
	$mvPackageId=$row["mv_package_id"];

	if ($ad_owner <> $_SESSION["valid_user"] AND !$admin_area)
	criticalError(LA_ERROR,LA_MUSTBEOWNER);

	if ($admin_area==1)
	$lAdminRegionSelected=getParam("admin_region_selected",$lAdRegion);
}

if ($admin_area==1)
$tplItem->assign("admin_region_options",getRegionTree(0,0,$lAdminRegionSelected));


$lCat=getParam("catid",$row["ad_cat_id"]);
if ($lAdRegion)
$lLevelArray=getLevelRegion($lAdRegion,"");

if (count($lLevelArray)==3)
{
	$lReg3Selected=$lLevelArray[1]["reg_id"];
	$lReg3Father=$lLevelArray[1]["reg_father"] . "_";

	$lReg2Selected=$lLevelArray[2]["reg_id"];
	$lReg2Father=$lLevelArray[2]["reg_father"];

	$lReg1Selected=$lLevelArray[3]["reg_id"];
}
else if (count($lLevelArray)==2)
{
	$lReg2Selected=$lLevelArray[1]["reg_id"];
	$lReg2Father=$lLevelArray[1]["reg_father"];
}

$lReg2Father=getParam("reg_1",$lReg2Father);
$lReg2Selected=getParam("reg_2",$lReg2Selected);

if ($lReg2Father && $lReg2Selected!="")
$lReg2String=$lReg2Father . "|" . $lReg2Selected;
else
$lReg2String=$lReg2Father;

$lReg3Father=getParam("reg_2",$lReg3Father);
$lReg3Selected=getParam("reg_3",$lReg3Selected);


if ($lReg3Father && $lReg3Selected!="")
$lReg3String=$lReg3Father . "|" . $lReg3Selected;
else
$lReg3String=$lReg3Father;

$tplItem->assign("reg_2_value",$lReg2String);
$tplItem->assign("reg_3_value",$lReg3String);


if ($lCat)
{
		$desmantelados = false;
	if($paquetesEspeciales[$lCat]==-1){
		$desmantelados = true;
	}
	$sql_top = "select cat_name,cat_fatherid,cat_cost ";

	if ($set_multilang_cat)
	{
		if ($_SESSION["la"]!="")
		$sql_top.=",lang_" . $_SESSION["la"];
		if ($set_language)
		$sql_top.=",lang_" . $set_language;
	}

	$sql_top.= " from $cat_tbl where cat_id = $lCat AND cat_allow_ads = 'on'";
	$result_1 = q ($sql_top);
	$row_1 = mysql_fetch_array($result_1);
	$lCatFatherID  = $row_1["cat_fatherid"];
	$lCatCost = $row_1["cat_cost"];

	// Check if user selected category exists
	if (!empty($_SESSION["la"]) AND $set_multilang_cat)
	{
		$lang_cat = "lang_" . $_SESSION["la"];
		if (!empty($row_1["$lang_cat"]))
		$lCatName = strEnc($row_1["$lang_cat"]);
	}
	// User has not set any prefered language..
	if (!$lCatName)
	{
		$lang_cat="lang_" . $set_language;
		if (!empty($row_1["$lang_cat"]))
		$lCatName = strEnc($row_1["$lang_cat"]); // Get default language, admin choise
		else
		$lCatName = strEnc($row_1["cat_name"]); // Last resort, use original name..
	}
}

if ($set_expire_days_option_list && $set_expire_days_option==1)
{
	$lExpireListArray=split(",","$set_expire_days_option_list");
	foreach ($lExpireListArray as $option)
	{
		$lExpireList.="<option value='$option'";
		if ($option==getParam("expire_days",""))
		$lExpireList.=" selected";
		$lExpireList.=">$option " . DAYS . "</option>";
	}
	$tplItem->assign("expire_list",$lExpireList);
}

$tplItem->assign("update_rq",getParam("update_rq",""));
$tplItem->assign("submit",getParam("submit",""));
$tplItem->assign("catname",$lCatName);
$tplItem->assign("show_form",1);

$lCurrentUser=$_SESSION["valid_user"];
if ($admin_area)
$lCurrentUser=$row["ad_owner"];

$lCurrentUser=(integer) $lCurrentUser;
$mainType=getPaqueteMainType($lCat);

if ($set_payments && getParam("update_rq","")=="" && $mainType!="" && !$admin_area)
{
	
	if (!getExpireStatus($lCurrentUser))
	{
		$mvPackageId = $_SESSION['package_selected_id'];
		
		if(isset($mvPackageId) && !empty($mvPackageId)){
			$sql="select pay_credits,pay_bold,pay_premium from $user_credits where user_id=$lCurrentUser and mainType=".$mainType;
			$sql.=" and package_id = ".$mvPackageId;
		}else{
			$sql="select sum(pay_credits) as pay_credits,sum(pay_bold) as pay_bold,sum(pay_premium) as pay_premium from $user_credits where user_id=$lCurrentUser and mainType=".$mainType;			
		}
		$res_user=q($sql);
		$row_user=mysql_fetch_array($res_user);
		$lPayCredits=$row_user["pay_credits"];
		if(empty($lPayCredits)) $lPayCredits=0;
		$lPayBold=$row_user["pay_bold"];
		$lPayPremium=$row_user["pay_premium"];

		if (!$lCatCost)
		$lCatCost=0;
			
		$tplItem->assign("set_payments",1);
		$tplItem->assign("pay_free_credits",$lPayCredits);
		$tplItem->assign("pay_catcost",$lCatCost);
		$tplItem->assign("pay_premium",$lPayPremium);
		if ($lPayCredits<$lCatCost)
		{
			/*JMR: Revisamos si al menos seleccionó un paquete.
			 * */
			$query="SELECT coalesce(sum(m.o_cantidad),0) as cantidad FROM mvial_orders m inner join mvial_packages p ON m.o_package=p.pid where o_status='0' and o_user=".$lCurrentUser."  and mainType=".$mainType;/*o_status='0' and*/
			$lRes=q($query);
			if($row_cat = mysql_fetch_array($lRes)){
				$orders=$row_cat["cantidad"];
				$tplItem->assign("have_an_order",1);
			}
			if($orders<1){
				$tplItem->assign("pay_out_of_credits",1);
				$tplItem->assign("show_form",0);
				$lErrorPay=1;
			}
		}
	}
}

$tplItem->assign("options",getRegionTree(0,0,$lSelected));
$lRegOptions="<option value=''>".LA_REGION_CHOOSE_FIRST."</option>";
$lRegOptions.=getRegionsForOneLevel(0,getParam("reg_1",$lReg1Selected),"");
$tplItem->assign("reg_1_options",$lRegOptions);

if (getParam("submit","")=="")
{
	$lTitle=$row["ad_title"];
	$lDescr=$row["ad_description"];
	$lUserID=$_SESSION["valid_user"];
}
else
{
	$lTitle=getParam("ad_title","");
	if ($set_wysiwyg_editor==1){
		$lDescr=caracteres_html(getParamHtml("ad_description",""));
	}else{
		$lDescr=getParam("ad_description","");
	}

	$lUserID=$_SESSION["valid_user"];

	$lAdMoneda=getParam("moneda","$AR");
	$lAdPrecio=getParam("precio","0");
	$lAdProvincia=getParam("provincia","");
	$extraModelo=getParam("modelo","");
	if(empty($_SESSION['package_selected_id']))
		$mvPackageId = getParam("packageId",0);
	else
		$mvPackageId = $_SESSION['package_selected_id'];
	$lAdLocalidad="NULL"; //EL ID para localidad no corre más por ahora, la localidad es un campo "especial" STRING
}
$lUserID=(integer) $lUserID;
$tplItem->assign("admin_area",$admin_area);
$tplItem->assign("ad_title",strEnc($lTitle));
if ($set_wysiwyg_editor==1){
	$tplItem->assign("ad_description",stripcslashes($lDescr));
	// $tplItem->assign("ad_description",mysql_real_escape_string  ($lDescr));
}else
$tplItem->assign("ad_description",strEnc($lDescr));
$tplItem->assign("catid",$lCat);
$tplItem->assign("ad_cat_id",$lCat);
$tplItem->assign("ad_id",getParam("ad_id",$ad_id));

//paso el precio, la moneda y la region al template
$tplItem->assign("ad_precio",$lAdPrecio);
$tplItem->assign("ad_moneda",$lAdMoneda);
//$tplItem->assign("ad_region",$lAdRegion);
$tplItem->assign("ad_provincia",$lAdProvincia);
$tplItem->assign("otraMarca",getParam("otraMarca",''));
//$tplItem->assign("ad_localidad_id",$lAdLocalidad);
$tplItem->assign("ad_localidad_str",$lAdLocalidadStr);
$tplItem->assign("extra_modelo",$extraModelo);
$tplItem->assign("PackageId",$mvPackageId);
$tplItem->assign("options_provincia",getProvincias($lAdProvincia));
$tplItem->assign("ad_moneda_options", getMonedaOptions($lAdMoneda));

// Find Extra fields in ad table and get values from not empty rows
$i=0;
$data="";
if ($lCat)
{
	$result_1 = q ("select cat_tpl from $cat_tbl where cat_id = $lCat");
	$row_cat = mysql_fetch_array($result_1);
	$cat_tpl = $row_cat["cat_tpl"];
}
if ($cat_tpl==0)
$cat_tpl=1;

if ($ad_id)
$lAdId=$ad_id;
//else
//	$lAdId=1;


/* Extra fields handling START */
$lFieldArray=getExtraFiltered($cat_tpl,$lAdId,"",$set_language);
//print_r($lFieldArray);

/*
 foreach ($lFieldArray as $lKey => $lValue)
 {
 echo $lValue["q_question"] ."<br />";
 //echo $lValue["selected_value"] ."<br />";

 foreach ($lValue["options"] as $lItems)
 {
 //echo $lItems["text"]. "<br />";
 print_r($lItems);
 echo "<hr>";
 }

 echo "<hr>";
 }
 */
//JMR
$marca_selected = "";
$isMarcaj = false;
$isMarcaa = false;
//END JMR
if (is_array($lFieldArray))
{
	foreach ($lFieldArray as $lKey => $lValue)
	{
		if ($lValue["q_question"]){
			$lFieldArray[$lKey]["q_question"]=(constant($lValue["q_question"]));
		}if ($lValue["q_catdescr"]){
			$lFieldArray[$lKey]["q_catdescr"]=(constant($lValue["q_catdescr"]));
		}if ($lValue["q_reg_exp_errormsg"]){
			$lFieldArray[$lKey]["q_reg_exp_errormsg"]=(constant($lValue["q_reg_exp_errormsg"]));
		}
		//JMR
		if($lFieldArray[$lKey]["q_type"]=="j"){
			$marca_selected =$lFieldArray[$lKey]["q_value"] ;
			$isMarcaj = true;
		}
		if($lFieldArray[$lKey]["q_type"]=="a"){
			$isMarcaa = true;
		}
		//END JMR
	}
}
//$lFieldArray[6]["options"][3]["selected_value"]=10;
//print_r($lFieldArray);
$tplItem->assign("extra_fields_array",$lFieldArray); // Add question to template
if (is_array($lFieldArray))
{
	//print_r($lFieldArray[6]["options"]);
	$lReturnResultArray=ExtraFieldsInputOperations($lFieldArray);
	$lInsertArray=$lReturnResultArray[0];	// Contains data to be inserted to extra
	$errorMsg=$lReturnResultArray[1]; 		// Contains error messages
}
/* Extra fields handling FINISH */

$tplItem->assign("decimal",$set_amount_decimal);

if (getParam("submit",""))
{
	// Simple Error Checking Start
	if (!$lTitle)
	$errorMsg.="<li>".LA_YOU_MUST ." <b>" . TITLE . "</b></li>";
	if (!$lReg2Selected && $set_region==1)
	$errorMsg.="<li>".LA_YOU_MUST ." <b>".LA_REGION."</b></li>";

	if (!$lDescr)
	$errorMsg.="<li>".LA_YOU_MUST ." <b>".DESCRIPTION."</b></li>";

	if (!$lCat)
	$errorMsg.="<li>".LA_YOU_MUST ." <b>".LA_CAT."</b></li>";

	if (!$lAdProvincia)
	$errorMsg.="<li>".LA_YOU_MUST ." <b>".EF_USR_PROVINCIA."</b></li>";

	// Check for banned words. If a banned word appear, raise warning
	$bad_words_list = split(",", $set_bad_words);
	foreach($bad_words_list as $bad)
	{
		if ($bad)
		{
			$result1 = eregi($bad,$lTitle);
			$result2 = eregi($bad,$lDescr);
		}

		if (!empty($result1) OR !empty($result2))
		$errorMsg.="<li>".LA_BAD_WORDS ." <b>$bad</b><br />";
	}

	// Simple Error Checking Completed
	$tplItem->assign("errorMsg", $errorMsg);
	if ($lReg3Selected)
	$lRegion=$lReg3Selected;
	else
	$lRegion=$lReg2Selected;

	if ($lRegion!="")
	$lRegion=eregi_replace("_","",$lRegion);
	if ($lAdminRegionSelected)
	$lRegion=$lAdminRegionSelected;


	if ($errorMsg)
	$tplItem->assign("show_form",1);
	else
	{
			$tplItem->assign("submit_ok",1);
			$tplItem->assign("show_form",0);
	
			if (getParamInt("ad_id",""))
			{
				## Modified Ad ##
				//logMsg("JMR","Antes de entrar al Update");
				updateAd($ad_id,$lCurrentUser,$lTitle,$lDescr,$lCat,"","","",$lInsertArray,$set_inform_admin_update,"$lRegion",$lAdPrecio,$lAdMoneda,$lAdLocalidad,$lAdProvincia);
			}
			else
			{
				## New Ad ##
				// If credit option and the user is not admin, reduce number of credits by one
				$lIsSpecial=0;
	
				// Check if the ad has already been posted (exaxtly same ad and user will raise warning)
				$result = q("select ad_id from $ads_tbl where ad_title = '".strToDb($lTitle) . "' AND ad_owner=$lUserID");
				$num_already_posted = mysql_num_rows($result);
				
				if ($num_already_posted>0)
				{
					echo "<p><b>" . formatString(LA_POSTED_BEFORE,array(strEnc(getParam("ad_title","")))) . "</b></p>";
					include_once("member_footer.php");
					include_once("footer_inc.php");
					exit;
				}
	
				if ($set_payments)
				{
					if ($lPayBold>0)
					$lIsSpecial=1;
	
					if ($lPayPremium>0)
					$lIsPremium=1;
					else
					$lIsPremium=0;
				}
				//JMR: Nuevas lineas de funcionalidad
				
				if (getParam("expire_days",""))
					$lNumberOfDays=(getParamInt("expire_days",1));
				elseif ($set_delete_after_x_days){
					$array = getPackageinfo($mvPackageId);
					$lNumberOfDays=$array['pdur'];
				}
				//logMsg("número de días","Los días son: ".$lNumberOfDays);				
				$ad_id=createAd($lUserID,$lTitle,$lDescr,$lCat,$lNumberOfDays,$lIsSpecial,$lIsPremium,$lInsertArray,$set_inform_admin_insert,"$lRegion",$lAdPrecio,$lAdMoneda,$lAdLocalidad,$lAdProvincia,$mvPackageId);
				if($ad_id<1){
					$tplItem->assign("pay_out_of_credits",1);
					$tplItem->assign("show_form",0);
					$lErrorPay=1;
				}
					
				if ($set_payments)
				{
					if (!getExpireStatus($lCurrentUser))
					{
						$sql="update $user_credits set pay_credits = pay_credits - $lCatCost where pay_credits>0";
						$sql.=" AND user_id = ".$_SESSION["valid_user"]." and mainType=".$mainType." and package_id = ".$mvPackageId;
						$res_pay=q($sql);
					}
					$sql="update $user_credits set pay_bold = pay_bold - 1 where pay_bold>0 ";
					$sql.=" AND user_id = ".$_SESSION["valid_user"]." and mainType=".$mainType." and package_id = ".$mvPackageId;
					$res_pay=q($sql);
							
					$sql="update $user_credits set pay_premium = pay_premium - 1 where pay_premium>0";
					$sql.=" AND user_id = ".$_SESSION["valid_user"]." and mainType=".$mainType." and package_id = ".$mvPackageId;
					$res_pay=q($sql);
	
					/*JMR: Este ultimo query borra directamente la entrada si no quedan más creditos de una categoria
					 * para el usuario logueado: Suspendido por ahora.*/
					//q("delete FROM $user_credits where pay_credits=0  AND user_id = ".$_SESSION["valid_user"]." and mainType=".$mainType);
						
				}
				/* JMR: Comentadas estas lineas para cambiar la funcionalidad: expire_days siempre indicará los dias de expiración
				 if ($set_expire_days_option==2 AND $set_delete_after_x_days)
					$lNumberOfDays=$set_delete_after_x_days;
					elseif ($set_expire_days_option==1 AND getParam("expire_days",""))
					$lNumberOfDays=(getParamInt("expire_days",1));
	
					*/
				if ($ad_id>0)
				{
					$tplItem->assign("submit_ok",$ad_id);
					$tplItem->assign("await_validation",$validation);
					//logMsg("JMR","Antes de motificar, values:".$lCat.' ; '.$catname.' ; '.$ad_id.' ; '.$lTitle.' ; '.strip_tags($lDescr).' ; '.$set_url);
					notifyMembersNewAd($lCat,$catname,$ad_id,$lTitle,strip_tags($lDescr),$set_url);
					//logMsg("JMR","Despues de notificar");
				}
					
			} // End of insert/update
			$tplItem->assign("picture_upload_enable", $set_image_upload);
			$tplItem->assign("ad_id", $ad_id);
			
			if(isset($_SESSION['transaction_oid']) && $_SESSION['transaction_oid']!=0)
			{
				//unset($_SESSION['transaction_oid']);

				$_SESSION['transaction_ad_id']=$ad_id;
				include 'upload_file.php';
				//JMR: cambio el orden, se pasa a la carga de imagenes antes de ir a pagar
				//include 'mvial_pay_center.php';
				exit;		
			}

	} // End IF NOT ERRORMSG Submit

	// End of submit information
}

$cat_list="";
if ($admin_area)
$cat_list=getCategoriesDD($lCatId,1);
else if ($ad_id && isset($lCatFatherID))
{
	$sql = "select cat_id,cat_name,cat_total";
	if ($set_multilang_cat)
	{
		$lLangSupportedArray=split(",",$set_multilang_cat);
		foreach ($lLangSupportedArray as $lItem)
		$sql.=",lang_" . $lItem;
	}
	$sql.= " from $cat_tbl where cat_allow_ads='on' AND cat_fatherid=$lCatFatherID";
	$sql = $sql . " order by cat_full_name";
	/**************************************/
	global $paquetesEspeciales;		
	/**************************************/
	$res = q($sql);

	while ($catr=mysql_fetch_array($res))
	{
		if($desmantelados)
			if($paquetesEspeciales[$catr["cat_id"]]!=-1) continue;
		else	
			if($paquetesEspeciales[$catr["cat_id"]]==-1) continue;
		$catid_sel = $catr["cat_id"];
		$lCatName="";
		if ($set_multilang_cat)
		$lCatName = $catr["lang_" . $set_language];
		if (!$lCatName)
		$lCatName = $catr["cat_name"]; // Last resort, use original name..


		$cat_list.= "<option value='$catid_sel'";
		if ($lCatId == $catid_sel)
		{
			$cat_list.= " selected";
		}
		if (!$catr["cat_total"])
			$num_ads=0;
		else
			$num_ads=$catr["cat_total"];
			
		$cat_list.= ">$lCatName ($num_ads) </option>";
	}
}
/*JMR: Estos flags son para optimizar los accesos a la base al obtener las marcas*/
if($isMarcaa){
	$marcasPorCat =  getMarcasByMercado($lCat,$marca_selected);
	$tplItem->assign("marcasPorCat",$marcasPorCat);
}
if($isMarcaj){
	$marcasPorMercado = getMarcasByMercadoUsingTipo($lCat,$marca_selected);
	$tplItem->assign("marcasPorMercado",$marcasPorMercado);
}

$tplItem->assign("cat_list",$cat_list);
if(empty($_SESSION['package_selected_id']) && getParam("update_rq","")=="" && getParamInt("ad_id","")==""){
	
	$paquetes = getUserPackages($mainType,$_SESSION["valid_user"]);
	$tplItem->assign("paquetes",$paquetes);
}
if(!empty($mvPackageId) && isFreePackage($mvPackageId)){
	$tplItem->assign("paqueteGratis",1);
}else{
	$tplItem->assign("paqueteGratis",0);
}
$tplItem->display("item.tpl");
if (!$admin_area)
{
	include_once("member_footer.php");
	include_once("footer_inc.php");
}
?>

